import base64
import hmac
import json
import datetime
import time

from hashlib import sha256

import redis
from apiview.views import View
from celery.worker.state import requests
from django.http import HttpResponse
from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin
from eventlet.green import urllib
from rest_framework.response import Response

from rest_framework.views import APIView


# Create your views here.
# 修改用户名
from myapp.models import User
# from myapp.test_queue import myq, RedisQueue, ThreadWork


# 码云client_id、client_secret
client_id = 'b59a2cefda529f2a768b5cdf811feb23d982c65aeb8c35ad4cb60e4abb44bd3b'
client_secret = 'fb771814737e36c018a3d5cc7b4d9644519bd3e1f6698e6e62c7a3d66886572b'


class UpdateUserName(APIView):

    def get(self, request):

        # 获取id
        uid = request.GET.get('id', None)
        # 获取用户名
        username = request.GET.get('username', None)

        # 判断数据库中有没有此用户
        user = User.objects.filter(username=username).first()
        if user:
            # 入队
            # myq.push((uid, username))

            return Response({'msg': '正在审核中，请耐心等待'})
        else:
            return Response({'msg': '没有此用户，无法进行修改用户名服务'})


# RBAC权限管理实现ABAC时间段权限
class GetUserInfo(APIView):

    def get(self, request):

        number = int(1)

        # 获取用户ID
        uid = request.GET.get('id')
        # 获取用户数据库信息
        user = User.objects.filter(id=uid).first()
        # 判断用户是否存在
        if user:
            if user.auth.id == number:
                return Response({'message': '超级管理员', 'auth': user.auth.id})
            else:
                # n_time = time.strftime("%H:%M:%S")
                # print(n_time)   # 18:02:03    xx:xx:xx

                # 范围时间
                d_time = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '9:00', '%Y-%m-%d%H:%M')
                d_time1 = datetime.datetime.strptime(str(datetime.datetime.now().date()) + '18:00', '%Y-%m-%d%H:%M')

                red = redis.Redis()
                red.set('1',d_time)
                red.set('2',d_time1)
                # 当前时间
                n_time = datetime.datetime.now()

                start = red.get(1)
                s = str(start, 'utf-8')
                time1 = datetime.datetime.strptime(s, '%Y-%m-%d %H:%M:%S')

                end = red.get(2)
                e = str(end, 'utf-8')
                time2 = datetime.datetime.strptime(e, '%Y-%m-%d %H:%M:%S')

                # 判断当前时间是否在范围时间内
                if n_time > time1 and n_time < time2:
                    t = 1
                    return Response({'message': '普通用户', 'auth': user.auth.id, 't': t})
                else:
                    t = 0
                    return Response({'message': '普通用户', 'auth': user.auth.id, 't': t})
        else:
            return Response({'message': '用户不存在'})


# ---------------------------------------------------------

# 自定义中间件
class Middleware(MiddlewareMixin):

    def process_request(self, request):

        num = int(request.GET.get('uid'))

        if num % 2 != 0:

            if request.path != '/users/':
                return HttpResponse(json.dumps({'message': '您没有该页面的访问权限', 'code': 400}, ensure_ascii=False))
            else:
                # return HttpResponseRedirect('/users/')
                pass
        else:

            if request.path != '/userdetail/':
                return HttpResponse(json.dumps({'message': '您没有该页面的访问权限', 'code': 400}, ensure_ascii=False))
            else:
                # return HttpResponseRedirect('/userdetail/')
                pass

    def process_view(self, request, view_func, view_args, view_kwargs):
        pass

    def process_exception(self, request, exception):
        pass

    def process_response(self, request, response):

        return response


# red = RedisQueue("redisqueue")
#
#
# class PutUser(APIView):
#
#     def post(self, request):
#         ThreadWork()
#
#         return Response({'message': '修改成功'})


# # 存入redis  入队
# class UpUser(APIView):
#
#     def get(self, request):
#
#         # 获取id
#         uid = request.GET.get('id', None)
#         # 获取用户名
#         username = request.GET.get('username', None)
#
#         # 判断数据库中有没有此用户
#         user = User.objects.filter(username=username).first()
#         if user:
#             # 入队
#             red.put((uid, username))
#
#             return Response({'msg': '正在审核中，请耐心等待'})
#         else:
#             return Response({'msg': '没有此用户，无法进行修改用户名服务'})


# # 出队
# class GetInfo(APIView):
#
#     def get(self, request):
#
#         if red.pop() != None:
#
#             return Response(info)
#
#         else:
#             return Response({'msg': '当前没有可以出队的数据'})


# 构造钉钉登录url
def ding_url(request):
    appid = 'dingoaukgkwqknzjvamdqh'
    redirect_uri = 'http://localhost:8000/dingding_back/'

    return redirect(
        'https://oapi.dingtalk.com/connect/qrconnect?appid=' + appid + '&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=' + redirect_uri)


# 构造钉钉回调方法
def ding_back(request):
    # 获取code
    code = request.GET.get("code")

    t = time.time()
    # 时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret = 'ly-AzMKMmCKQP3geaILT_An32kEfKO3HeOtApy5CgKwjytevVZC0WYsT2gxMB160'
    # 构造签名
    signature = base64.b64encode(
        hmac.new(appSecret.encode('utf-8'), timestamp.encode('utf-8'), digestmod=sha256).digest())
    # 请求接口，换取钉钉用户名
    payload = {'tmp_auth_code': code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=' + urllib.parse.quote(
        signature.decode("utf-8")) + "&timestamp=" + timestamp + "&accessKey=dingoaukgkwqknzjvamdqh",
                        data=json.dumps(payload), headers=headers)

    res_dict = json.loads(res.text)
    print(res_dict)

    # 判断
    user = User.objects.filter(username=res_dict['user_info']['nick']).first()

    if user:

        return redirect('http://localhost:8080/mylogin_two?uid=' + str(user.id) + "&username=" + user.username)

    else:

        user = User(username=res_dict['user_info']['nick'])
        user.save()
        user_obj = User.objects.filter(username=res_dict['user_info']['nick']).first()

        return redirect('http://localhost:8080/mylogin_two?uid=' + str(user_obj.id) + "&username=" + user_obj.username)


# 拼接码云三方url
class Gitee(View):

    def get(self, request):
        return redirect(
            'https://gitee.com/oauth/authorize?client_id=' + client_id + '&redirect_uri=http://localhost:8000/gitee_back/&response_type=code&scope=user_info')


# 码云回调url
class GiteeBack(View):

    def get(self, request):

        code = request.GET.get("code", None)

        r = requests.post(
            "https://gitee.com/oauth/token?grant_type=authorization_code&code=" + code + "&client_id=" + client_id + "&redirect_uri=http://localhost:8000/gitee_back/&client_secret=" + client_secret)
        print(r.text)

        res_dict = json.loads(r.text)
        access_token = res_dict['access_token']

        s = requests.get("https://gitee.com/api/v5/user?access_token=" + access_token)
        s_dict = json.loads(s.text)

        user = User.objects.filter(username=s_dict['name']).first()

        if user:

            return redirect('http://localhost:8080/mylogin_gitee?uid=' + str(user.id) + '&username=' + user.username)

        else:

            user = User(username=s_dict['name'])

            user.save()
            user_obj = User.objects.filter(username=s_dict['name']).first()

            return redirect(
                'http://localhost:8080/mylogin_gitee?uid=' + str(user_obj.id) + '&username=' + user_obj.username)


